import { getAnswerListAPI } from '@/apis/answer'
import { useRoute } from 'vue-router'
import { ref, onMounted } from 'vue'

export default function useAnswerInfo() {

  const answerInfo = ref([])
  const route = useRoute()
  const initOrder = route.query.order || 'newest'

  onMounted(async () => retrieveData(initOrder))

  function refreshAnswerData(type) {
    answerInfo.value.length = 0
    retrieveData(type)
  }

  function retrieveData(order) {
    getAnswerListAPI(route.params.id, order)
      .then(res => {
        // 和现有的数据合并
        answerInfo.value = answerInfo.value
          .concat(res.data.records)
          .sort((a, b) => b.adopted - a.adopted)
      })
      .catch(() => null)
  }

  return {
    answerInfo,
    refreshAnswerData
  }
}